package handler

import (
	"api-getway/global"
	pb "api-getway/internal/pb"
	"api-getway/internal/resp"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwts "github.com/winksai/jwt/jwt"
	"net/http"
	"time"
)

const ExpiresAt = time.Second * 60 * 60 * 24
const SecretKey = "this is a secretKey"

func Login(c *gin.Context) {
	mobile := c.PostForm("mobile")
	code := c.PostForm("code")
	login, err := global.UserClient.Login(c, &pb.LoginRequest{
		Mobile: mobile,
		Code:   code,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "登录失败" + err.Error()})
		return
	}

	claims := jwts.CustomClaims{
		ID: uint(login.Uid),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: int64(ExpiresAt),
		},
	}
	newJWT := jwts.NewJWT(SecretKey)
	token, err := newJWT.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "token生成失败" + err.Error()})
		return
	}
	c.JSON(http.StatusOK, resp.Res{
		Code: 200,
		Msg:  "登录成功",
		Data: map[string]interface{}{"token": token},
	})
}
